package com.example.cardgame

class CardGame(private val numPairs: Int) {

    val cards: MutableList<Card> = mutableListOf()
    private var indexOfSingleSelectedCard: Int? = null

    var allCardsMatched: Boolean = false

    init {
        val cardIds = (1..numPairs).toList() + (1..numPairs).toList()
        cardIds.shuffled().forEach { id ->
            cards.add(Card(id))
        }
    }

    // 返回值为一个枚举，表示翻牌结果
    fun flipCard(index: Int): FlipResult {
        val selectedCard = cards[index]

        // 忽略已经匹配的牌
        if (selectedCard.isMatched) {
            return FlipResult.NoAction
        }

        var result = FlipResult.NoAction

        // 如果没有翻开的牌，翻开当前牌
        if (indexOfSingleSelectedCard == null) {
            resetCards()
            selectedCard.isFlipped = true
            indexOfSingleSelectedCard = index
            result = FlipResult.Flipped
        } else {
            // 如果已经有一张翻开的牌，检查是否匹配
            val matched = checkForMatch(indexOfSingleSelectedCard!!, index)
            indexOfSingleSelectedCard = null
            result = if (matched) FlipResult.MatchFound else FlipResult.NoMatch
        }

        // 检查是否所有卡片都已匹配
        allCardsMatched = cards.all { it.isMatched }

        return result
    }

    private fun checkForMatch(index1: Int, index2: Int): Boolean {
        if (cards[index1].id == cards[index2].id) {
            cards[index1].isMatched = true
            cards[index2].isMatched = true
            cards[index2].isFlipped = true
            return true
        } else {
            cards[index2].isFlipped = true
            return false
        }
    }

    private fun resetCards() {
        cards.forEach { card ->
            if (!card.isMatched) {
                card.isFlipped = false
            }
        }
    }
}

// 定义翻牌结果的枚举
enum class FlipResult {
    NoAction,    // 没有操作（例如点击已匹配的牌）
    Flipped,     // 翻开了第一张牌
    MatchFound,  // 找到了匹配
    NoMatch      // 不匹配
}
